package com.commit.service.impl;

import com.commit.domain.Question;
import com.commit.domain.User;
import com.commit.mapper.QuesMapper;
import com.commit.ownException.NotFoundException;
import com.commit.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @author:zyh
 * @Time:2021-02-28-9:56
 * @email:1269231889@qq.com
 */
@Service
public class QuesServiceImpl implements QuestionService {

    @Autowired
    private QuesMapper quesMapper;

    @Override
    public void save(Question question, HttpSession session) {
        question.setCreateTime(new Date());
        User user = (User) session.getAttribute("user");
        if (user != null) {
            question.setUserId(user.getId());
            quesMapper.save(question);
        } else {
            throw new NotFoundException("没有对应用户");
        }
    }

    @Override
    public List<Question> findAll(Integer currentPage, Integer pageCount, String title) {
        int begin = (currentPage - 1) * pageCount;
        return quesMapper.findAll(begin, pageCount, title);
    }

    @Override
    public Integer getTotal(Integer pageCount, String title) {
        if (title == null) title = "";
        Integer total = quesMapper.getTotal(title);
        return (total - 1) / pageCount + 1;
    }

    @Override
    public void update(Question question) {
        if(question==null) throw new NotFoundException("问题内容不能为空");
        quesMapper.update(question);
    }

    @Override
    public void del(Integer id) {
        if(quesMapper.findById(id)==null){
            throw new NotFoundException("没有对应问题");
        }
        quesMapper.del(id);
    }

    @Override
    public Question findById(Integer id) {
        Question byId = quesMapper.findById(id);
        if(byId==null)  throw new NotFoundException("没有对应问题");
        return quesMapper.findById(id);
    }

    @Override
    public List<Question> findByTitle(String title) {
        title = (title.length()>20)?title.substring(0,20):title;
        List<Question> byTitle = quesMapper.findByTitle(title);
        if(byTitle==null||byTitle.isEmpty()){
            throw new NotFoundException("没有");
        }else{
            return byTitle;
        }
    }

    @Override
    public List<Question> findByTimeAndTitle(String title, Date begin,Date end) {
        List<Question> titleAndTime = quesMapper.findByTitleAndTime(title, begin, end);
        if(titleAndTime==null||titleAndTime.isEmpty()){
            throw new NotFoundException("没有问题");
        }
        return titleAndTime;
    }

}
